package com.itheima.filter;


import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //转换请求响应的对象
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse rep = (HttpServletResponse) servletResponse;
        //1.获取请求的路径
        String url = req.getRequestURI();
        log.info("请求的路径为:{}", url);
        //2.判断是否是登陆请求(是就放行)
        if (url.contains("login")) {
            log.info("登录请求,放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //3.判断jwt令牌是否有且合法(合法放行)
        //获取jwt令牌
        String jwt = req.getHeader("token");
        //这个方法表示这个字符串是否有长度(前面加个!代表没长度),也就侧面判断了是否为null或者空串
        if (!StringUtils.hasLength(jwt)) {
            log.info("请求头token为空,返回未登录信息");
            Result error = Result.error("NOT_LOGIN");
            //手动转换json对象
            String notLogin = JSONObject.toJSONString(error);
            //把未登录信息响应给前端
            rep.getWriter().write(notLogin);
            return;
        }
            //解析失败就会报错
            try {
                JwtUtils.parseJWT(jwt);
            } catch (Exception e) {
                //解析失败的情况,返回未登录的信息
                e.printStackTrace();
                log.info("令牌解析失败,返回未登录信息");
                Result error = Result.error("NOT_LOGIN");
                //手动转换json对象
                String notLogin = JSONObject.toJSONString(error);
                //把未登录信息响应给前端
                rep.getWriter().write(notLogin);
                return;
            }
            log.info("令牌合法,放行");
            filterChain.doFilter(servletRequest, servletResponse);
    }
}
